package com.biboheart.brick.adapter.converts;

import com.biboheart.brick.adapter.Converter;
import com.biboheart.brick.adapter.TypeConverter;

import java.util.regex.Pattern;

/**
 * 分割转换器, 辅助参数为分割符和索引，索引从0开始，默认分隔符为","，默认索引为0
 * 例如：
 * 输入为"15|7|30|35"，辅助参数为"|1"，转换为"7"
 */
public class SplitConverter implements Converter {
    @Override
    public <T> T convert(Object input, String auxiliary, Class<T> valueType) {
        if (null == input || null == auxiliary) {
            return null;
        }
        if (auxiliary.isEmpty()) {
            return TypeConverter.convert(input, valueType);
        }
        String indexStr = auxiliary.contains(",") ? auxiliary.substring(auxiliary.lastIndexOf(",") + 1) : null;
        int index = 0;
        String regex = auxiliary;
        Pattern pattern = Pattern.compile("[0-9]*");
        if (null != indexStr && pattern.matcher(indexStr).matches()) {
            index = Integer.parseInt(indexStr);
            regex = auxiliary.substring(0, auxiliary.lastIndexOf(","));
        }
        String val = TypeConverter.convert(input, String.class);
        String[] strArr = val.split(regex);
        if (strArr.length <= index) {
            return TypeConverter.convert(strArr[strArr.length - 1], valueType);
        }
        return TypeConverter.convert(strArr[index], valueType);
    }
}
